﻿// BookRules.shared.cs
//

using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Principal;

namespace BookClub.Web.DataModel {

    public static partial class BookRules {

        // Validates that the operation being performed on the book is being done in the context
        // of the book's owner.
        public static AuthorizationResult IsBookOwner(IPrincipal user, AuthorizationContext authorizationContext) {
            Book book = (Book)authorizationContext.Instance;
            User userInfo = (User)authorizationContext.Items[typeof(User)];

            if (user != null) {
                Book dbBook = null;
                using (BookClubEntities bookClubEntities = new BookClubEntities()) {
                    dbBook = bookClubEntities.Books.Where(b => b.BookID == book.BookID).FirstOrDefault();
                }

                if ((dbBook != null) && (dbBook.MemberID == userInfo.MemberID)) {
                    return AuthorizationResult.Allowed;
                }
            }

            return new AuthorizationResult("You must be the owner of the book to make a change.");
        }
    }
}
